/*
	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Library General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
*/

#include <QObject>

#include "searchboximpl.h"
#include "datamodel.h"
#include "constantes.h"

//
SearchBoxImpl::SearchBoxImpl( QWidget * parent, Qt::WFlags f)
        : QWidget(parent, f)
{
    setupUi(this);

    m_searchThread = NULL;
    m_tree = NULL;

    m_pageRoot = NULL;
    m_categoryRoot = NULL;

    m_results = new QList<SearchResultItem *>();

    connect(twResult, SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)), this, SLOT(onTreeDblClick(QTreeWidgetItem *, int)));
}
//

void SearchBoxImpl::setTree(QTreeWidget *tree)
{
    m_tree = tree;
}

void SearchBoxImpl::setModel(Model *model)
{
    m_model = model;
}

/* Clear previous search results. */
void SearchBoxImpl::purgeResults()
{
    SearchResultItem *item;
    for (int i = 0; i < m_results->size(); i++)
    {
        item = m_results->at(i);
        delete item;
    }
    m_results->clear();
}

/* When the user click on a result, get the clicked item and notify. */
void SearchBoxImpl::onTreeDblClick(QTreeWidgetItem *treeItem, int col)
{
    if ((treeItem != m_categoryRoot) &&
            (treeItem != m_pageRoot))
    {   
    	int dataIndex = treeItem->data(0, Qt::UserRole).toUInt(); 
    	SearchResultItem *resultItem = m_results->at(dataIndex);
        emit onSearchSelectionTriggered(resultItem->dataNode, resultItem->inPos, m_searchTerm.length());
    }
}

/* Search finished (notified by the search thread) : update the result UI. */
void SearchBoxImpl::onSearchFinished()
{
    QTreeWidgetItem *childItem;
    SearchResultItem* item;
	int nbPageHit = 0;
	int nbCategoryHit = 0;
    
    /* Add root categories. */ 
    m_categoryRoot = new QTreeWidgetItem(twResult);
    m_categoryRoot->setIcon(0, QIcon (twResult->style()->standardPixmap(QStyle::SP_DirOpenIcon)));
    m_categoryRoot->setText(0, tr("Categories"));
    m_pageRoot = new QTreeWidgetItem(twResult);
    m_pageRoot->setIcon(0, QIcon (twResult->style()->standardPixmap(QStyle::SP_FileIcon)));
    m_pageRoot->setText(0, tr("Pages"));

	/* Loop on results. */
    for (int i = m_results->size() - 1; i >= 0; i--)
    {
        item = m_results->at(i);
        QString type = item->stType;

        if (type == Constantes::TAG_CATEGORY)
        {
        	nbCategoryHit++;
            childItem = new QTreeWidgetItem(m_categoryRoot);
            childItem->setText(0, item->stTitle);
            childItem->setText(1, item->stContext);
            childItem->setData(0, Qt::UserRole, i);
        }
        else if (type == Constantes::TAG_PAGE)
        {
        	nbPageHit++;
            childItem = new QTreeWidgetItem(m_pageRoot);
            childItem->setText(0, item->stTitle);
            childItem->setText(1, item->stContext);
            childItem->setData(0, Qt::UserRole, i);
        }
    }
    m_categoryRoot->setText(1, QString(tr("%1 Hit(s)")).arg(QString::number(nbCategoryHit)));
    m_pageRoot->setText(1, QString(tr("%1 Hit(s)")).arg(QString::number(nbPageHit)));
    btnSearch->setEnabled(true);
}

/* Search request. */
void SearchBoxImpl::on_btnSearch_clicked()
{
    if ((m_tree != NULL) &&
            (m_model != NULL) &&
            (leSearchField->text() != ""))
    {
    	/* Create search thread if necessary. */
        if (m_searchThread == NULL)
        {
            m_searchThread = new SearchThread(m_tree, m_model);
            qRegisterMetaType< QList<SearchResultItem *> *>("QList<SearchResultItem *> *");
            /* The search thread emit a "searchFinished" signal when search si over. */
            connect(m_searchThread, SIGNAL(searchFinished( )), this, SLOT(onSearchFinished( )));
        }

        if (!m_searchThread->isSearching())
        {
            btnSearch->setEnabled(false);
			
			/* Purge previous results. */
            purgeResults();
            twResult->clear();
            
            m_searchTerm = leSearchField->text();

            m_searchThread->initSearch(	m_results,
                                        m_searchTerm,
                                        cbWholeWord->isChecked(),
                                        cbCaseSensitive->isChecked(),
                                        cbScopePage->isChecked(),
                                        cbScopeCategory->isChecked(),
                                        cbScopeTags->isChecked());
			
            tabPanel->setCurrentIndex(1);

            m_searchThread->start();
        }
    }
}
